package com.atguigu.gmall.common.interceptor;

import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * @Description: 远程调用拦截器
 * @Author: Mr.Cao
 * @DateTime: 2021/10/19 19:26
 * BMW F750GS
 **/
public class FeignInterceptor implements RequestInterceptor {


    @Override
    public void apply(RequestTemplate requestTemplate) {
        //在SpringIOC容器  任意位置获取HttpServletRequest
        ServletRequestAttributes servletRequestAttributes =
                (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (servletRequestAttributes!=null){
            //获取请求对象
            HttpServletRequest request = servletRequestAttributes.getRequest();
            if (request != null){
                String userId = request.getHeader("userId");
                String tempUserId = request.getHeader("userTempId");
                if (!StringUtils.isEmpty(userId)){
                    //设置到请求头中
                    requestTemplate.header("userId",userId);
                }
                if (!StringUtils.isEmpty(tempUserId)){
                    requestTemplate.header("userTempId",tempUserId);
                }
            }
        }

    }
}
